<template>
  <BasicDrawer @register="registerBaseDrawer" title="接收人管理" width="1000" destroyOnClose>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-button type="primary" @click="handleSelect">选择接收人</a-button>
      </template>

      <template #email="{ record }">
        <span :class="`${prefixCls}-verify-target`">{{ record.email }}</span>
        <a-tooltip placement="topLeft" v-if="!record.emailStatus || record.emailStatus === VerifyStatus.NO_VERIFY">
          <template #title>
            <span>
              邮箱未验证，不能接收消息。
              <a @click="handleEmailVerify(record)">发送验证</a>
            </span>
          </template>
          <ExclamationCircleTwoTone two-tone-color="#FAAD14" />
        </a-tooltip>
      </template>

      <template #phone="{ record }">
        <span :class="`${prefixCls}-verify-target`">{{ record.phone }}</span>
        <a-tooltip placement="topLeft" v-if="!record.phoneStatus || record.phoneStatus === VerifyStatus.NO_VERIFY">
          <template #title>
            <span>
              手机未验证，不能接收消息。
              <a @click="handlePhoneVerify(record)">发送验证</a>
            </span>
          </template>
          <ExclamationCircleTwoTone two-tone-color="#FAAD14" />
        </a-tooltip>
      </template>

      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
  </BasicDrawer>
  <SelectReceiverModal @register="registerSelectReceiverModal" @select="selectOk" />
  <VerifyModal @register="registerVerifyModal" :submitCallback="handleSubmitVerify" :biz-type="BizType.MSG_RECEIVER" />
  <ReceiverDrawer @register="registerDrawer" @success="reload" showFooter />
</template>
<script lang="ts" setup>
  import { ref, watch, unref } from "vue"
  import { BasicTable, useTable, TableAction } from "/@/components/Table"
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import { BizType } from "/@/api/sys/model/msgPushModel"
  import { ExclamationCircleTwoTone } from "@ant-design/icons-vue"
  import { listMsgSubscriber, saveMsgSubscriber, deleteMsgSubscriber } from "../api"
  import { receiverColumns } from "../data"
  import SelectReceiverModal from "../../receiver/components/SelectReceiverModal.vue"
  import { sendCaptcha, checkCaptcha } from "../../receiver/receiver.api"
  import { VerifyStatus } from "../../receiver/receiver.data"
  import { VerifyModal } from "/@/components/BizVerify"
  import { useDesign } from "/@/hooks/web/useDesign"
  import ReceiverDrawer from "../../receiver/components/ReceiverDrawer.vue"

  const { prefixCls } = useDesign("msg-receiver")
  const emit = defineEmits(["register"])

  const checkedKeys = ref<Array<string | number>>([])
  const noticeId = ref("")
  const [registerBaseDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    noticeId.value = data.record.id
    setProps({ searchInfo: { noticeId: data.record.id } })
    reload()
  })
  const [registerVerifyModal, { openModal: openVerifyModal }] = useModal()
  const [registerSelectReceiverModal, { openModal: openSelectReceiverModal }] = useModal()
  const [registerDrawer, { openDrawer }] = useDrawer()
  const [registerTable, { reload, setProps }] = useTable({
    title: "接收人列表",
    api: listMsgSubscriber,
    columns: receiverColumns,
    striped: true,
    immediate: false,
    useSearchForm: false,
    showTableSetting: true,
    clickToRowSelect: false,
    bordered: false,
    showIndexColumn: false,
    tableSetting: { fullScreen: true },
    canResize: false,
    rowKey: "id",
    actionColumn: {
      width: 100,
      title: "操作",
      dataIndex: "action",
      slots: { customRender: "action" },
      fixed: undefined,
    },
  })

  const rowSelection = {
    type: "checkbox",
    columnWidth: 50,
    selectedRowKeys: checkedKeys,
    onChange: onSelectChange,
  }

  function onSelectChange(selectedRowKeys: (string | number)[], selectionRows) {
    checkedKeys.value = selectedRowKeys
  }

  async function handleDelete(record) {
    await deleteMsgSubscriber({ receiverIds: [record.id], noticeIds: [noticeId.value], name: record.name }, reload)
  }

  /**
   * 选择接收人
   */
  function handleSelect() {
    openSelectReceiverModal(true)
  }

  /**
   * 添加接收人
   */
  async function selectOk(val) {
    await saveMsgSubscriber({ noticeIds: [noticeId.value], receiverIds: val })
    reload()
  }

  const handleSubmitVerify = async (data) => {
    console.log("submitVerify: ", data)
    await checkCaptcha(data)
    reload()
  }

  const handleEmailVerify = (record) => {
    openVerifyModal(true, {
      verifyType: "verifyEmail",
      toUser: record.email,
      apiParams: { receiverId: record.id },
      api: sendCaptcha,
    })
  }

  const handlePhoneVerify = (record) => {
    openVerifyModal(true, {
      verifyType: "verifyPhone",
      toUser: record.phone,
      apiParams: { receiverId: record.id },
      api: sendCaptcha,
    })
  }

  /**
   * 编辑
   */
  function handleEdit(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
    })
  }

  function getTableAction(record) {
    return [
      {
        label: "移除",
        color: "error",
        onClick: handleDelete.bind(null, record),
      },
      {
        label: "编辑",
        onClick: handleEdit.bind(null, record),
      },
    ]
  }
</script>

<style lang="less">
  @prefix-cls: ~"@{namespace}-msg-receiver";

  .@{prefix-cls}-verify-target {
    margin-right: 2px;
    margin-left: 2px;
  }
</style>
